package timing.ukulele.common.util;


import timing.ukulele.common.dictionary.CodeValueEnum;

import java.util.ArrayList;
import java.util.List;

public final class DictionaryUtil {
    public static <T extends CodeValueEnum> T get(Class<T> enumClass, String value, T defaultValue) {
        T[] valueEnums = enumClass.getEnumConstants();
        for (T e : valueEnums) {
            if (e.getCode().equals(value)) {
                return e;
            }
        }
        return defaultValue;
    }

    public static <T extends CodeValueEnum> T get(Class<T> enumClass, String value) {
        return get(enumClass, value, null);
    }

    public static <T extends Enum<T>> T get(Class<T> enumClass, String name, T defaultValue) {
        T e = Enum.valueOf(enumClass, name);
        return null == e ? defaultValue : e;
    }

    public static <T extends CodeValueEnum> String get(Class<T> enumClass, Object code) {
        T[] valueEnums = enumClass.getEnumConstants();
        for (T e : valueEnums) {
            if (e.getCode().equals(code)) {
                return e.getValue();
            }
        }
        return null;
    }

    public static <T extends CodeValueEnum> String[] all(Class<T> enumClass) {
        T[] valueEnums = enumClass.getEnumConstants();
        List<String> values = new ArrayList<>(valueEnums.length);
        for (T e : valueEnums) {
            values.add(e.getValue());
        }
        return values.toArray(new String[0]);
    }
}
